import { useSelector, useDispatch } from 'react-redux';
import { useEffect } from 'react';
import { setList, deleteById } from '../store/modules/listStore';

const List = () => {
  useEffect(() => {
    const request = async () => {
      const response = await fetch('/db/persons.json');
      const json = await response.json();
      dispatch(setList(json));
    };
    request();
  }, []);

  const { list } = useSelector(state => state.list);

  const dispatch = useDispatch();

  const lis = list.map(item => (
    <li key={item.id} className="flex items-center py-[10px] odd:bg-green-100 even:bg-blue-100 hover:odd:bg-green-200 hover:even:bg-blue-200">
      <p className="ml-[30px] mr-auto">{item.name}</p>
      <button className="mr-[30px] py-[8px] px-[16px] rounded-[8px] select-none cursor-pointer active:bg-red-500 text-[black] font-bold bg-red-400" onClick={() => dispatch(deleteById(item.id))}>删除</button>
    </li>
  ));

  return (
    <ul className="mt-[50px] mx-auto w-[400px] flex flex-col mb-[200px]">
      {lis}
    </ul>
  );
};

export default List;